#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"../include/vfs.h"

int searchfile(char filename[], char filepath[])
{

	FILE *fp,*out;
	bst *search=NULL;
	np match=NULL;
	int i,num_matches=0;

	if(!valid_name(filename))
		return 4;

	fp = fopen(filesystem_name,"r+b");

	header=malloc(sizeof(Header));

	fread(header,sizeof(Header),1,fp);

	out = fopen(filepath,"a");

	if(out==NULL)
		return 1;

		
		match = hash_search(filename);
		

		if(match==NULL)
		{
			fseek(out,0,SEEK_END);
			fprintf(out,"\n NO MATCHES FOUND");
			return 0;
		}

		if(strcmp(filepath,"")==0)
			return 2;
	
		else
		{	
			while(match!=NULL)
			{
				
	
				if(strcmp(match->fdes->filename,filename)==0 || strstr(match->fdes->filename,filename)!=NULL)
				{	
					num_matches++;
					fseek(out,0,SEEK_END);
					fprintf(out,"\n %s",match->fdes->filename);
					fprintf(out,"\n \t %s",match->fdes->path);
	
				}
				
				match = match->next;
			}
		}
		

		fseek(out,0,SEEK_END);
		fprintf(out,"\n %d MATCHES FOUND \n",num_matches);

		rewind(fp);
		
		fwrite(header,sizeof(Header),1,fp);

		fclose(fp);	


	return 0;
}

















		

